﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.IO;
using System.Diagnostics;
using System.Globalization;
using PrintDataGrid;
using System.Configuration;

namespace ManagingBakery
{
    public partial class Form1 : Form
    {
        private bool IsLoggedIn = false;

        DataTable BranchesData = null;
        bool isNewItem = false;

        DateTime dtDateSelected = DateTime.Now;
        string branchSelected;
        bool isBranchSelected;

        private const int VERSION = 1;
        private const int APPID = 3;

        #region .Ctr
        public Form1()
        {
            InitializeComponent();

            /*//Setting TimeLines to Operate the Application
            DateTime currentDate = GetCurrentDateTime();

            //June To Aug
            if (!(currentDate.Month >= 5 && currentDate.Month <= 7))
            {
                MessageBox.Show("Invalid Application Request!!! Contact Administrator.", "Invalid Application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }*/

            //Validating the version
            if (!DBHelper.ValidateVersion(APPID, VERSION))
            {
                MessageBox.Show("Upgrade to Latest Version !", "Obsolete Version", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }

            //Disabling the Tab Control Headers
            tabControl1.Appearance = TabAppearance.FlatButtons;
            tabControl1.ItemSize = new Size(0, 1);
            tabControl1.SizeMode = TabSizeMode.Fixed;
        }
        #endregion

        #region Private Methods

        private DateTime GetCurrentDateTime()
        {
            try
            {
                WebRequest request = WebRequest.Create(@"http://developer.yahooapis.com/TimeService/V1/getTime?appid=Test");
                // request.Proxy = new WebProxy("PROXYSERVERNAME", 8080); // You may or may not need this 
                WebResponse response = request.GetResponse();

                Double currentTimeStamp = 0;
                using (Stream stream = response.GetResponseStream())
                {
                    using (XmlTextReader xmlReader = new XmlTextReader(stream))
                    {
                        while (xmlReader.Read())
                        {
                            switch (xmlReader.NodeType)
                            {
                                case XmlNodeType.Element:
                                    if (xmlReader.Name == "Timestamp")
                                    {
                                        currentTimeStamp = Convert.ToDouble(xmlReader.ReadInnerXml());
                                    }
                                    break;
                            }
                        }

                        xmlReader.Close();
                    }
                }

                DateTime yahooDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0);
                return yahooDateTime.AddSeconds(currentTimeStamp).AddHours(5).AddMinutes(30);
            }
            catch (Exception ex)
            {
                WriteToEventViewer("Couldn't get the current time from internet. " + ex.Message);
                return DateTime.Now;
            }
        }

        private void WriteToEventViewer(string message)
        {
            try
            {
                if (!EventLog.SourceExists("KSBakery"))
                    EventLog.CreateEventSource("KSBakery", "KSBakery");
                EventLog.WriteEntry("KSBakery", message, EventLogEntryType.Error);
            }
            catch (Exception)
            { }
        }

        #endregion

        #region Update Stock

        private void btnUpdateStockByBranch_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (BranchesData == null)
                        BranchesData = DBHelper.GetBranches();
                    cmbBranchUpdate.DataSource = BranchesData;
                    cmbBranchUpdate.DisplayMember = "BranchName";
                    cmbBranchUpdate.ValueMember = "BranchID";
                    dg.DataSource = null;
                    tabControl1.SelectTab(2);

                    cmbBranchUpdate.SelectedIndex = 0;
                    txtItem.Clear();
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnGetStock_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                dg.DataSource = DBHelper.GetStockByBranchToUpdate(cmbBranchUpdate.SelectedValue.ToString(), txtItem.Text);
                if (dg.Rows.Count > 0)
                {
                    dg.Columns[0].Width = 50;
                    dg.Columns[1].Width = 230;
                    dg.Columns[0].ReadOnly = true;
                    dg.Columns[1].ReadOnly = true;
                    dg.Columns[2].Visible = false;
                    dg.Columns[3].ReadOnly = true;
                    dg.Focus();
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Cursor.Current = Cursors.Default;
        }

        private void dg_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (dg.SelectedRows.Count > 0)
                {
                    dg.SelectedRows[0].Cells[3].Selected = true;
                    if (e.KeyChar > 47 && e.KeyChar < 58)
                    {
                        dg.SelectedRows[0].Cells[3].Value = e.KeyChar;
                        dg.BeginEdit(false);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dg_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string value = dg[e.ColumnIndex, e.RowIndex].Value.ToString();

                double result = 0;

                if (double.TryParse(dg[e.ColumnIndex, e.RowIndex].Value.ToString(), out result))
                {
                    if ((bool)dg[2, e.RowIndex].Value)
                        dg[e.ColumnIndex, e.RowIndex].Value = result;
                    else
                        dg[e.ColumnIndex, e.RowIndex].Value = (int)result;
                }
                else
                {
                    dg[e.ColumnIndex, e.RowIndex].Value = "0";
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdateStock_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (dg != null && dg.Rows.Count > 0)
                {
                    if (DialogResult.OK == MessageBox.Show("Do you want to update the stock for " + cmbBranchUpdate.Text + " Branch?", "Update Stock", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        int res = DBHelper.UpdateStockAtCentral(dg.DataSource as DataTable, cmbBranchUpdate.SelectedValue.ToString());
                        if (res == 0)
                        {
                            MessageBox.Show("Stock Updated Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            dg.DataSource = null;
                            txtItem.Clear();
                        }
                        else if (res == -2)
                        {
                            MessageBox.Show("Nothing to Update. Enter Valid Values.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        else
                        {
                            MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        Cursor.Current = Cursors.Default;
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGetAllItems_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                dg.DataSource = DBHelper.GetStockToUpdate();
                dg.Columns[0].Width = 60;
                dg.Columns[0].ReadOnly = true;
                dg.Columns[1].Width = 340;
                dg.Columns[1].ReadOnly = true;
                dg.Columns[2].Visible = false;
                dg.Columns[3].Width = 80;
                dg.Focus();
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSetZeros_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (DataGridViewRow row in dg.Rows)
                {
                    row.Cells[3].Value = "0";
                }
            }
            catch (Exception)
            { }
        }

        #endregion

        #region Modify Items

        private void btnItems_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {

                //DataTable dt = DBHelper.GetBranches();
                DataTable dt = new DataTable();
                dt.Columns.Add("BranchID");
                dt.Columns.Add("BranchName");

                dt.Rows.Add(0, "General");
                //dt.Rows.Add(-1, "CSC");
                dt.Rows.Add(-2, "Sangareddy");

                cmbBranchItems.DataSource = dt;
                cmbBranchItems.DisplayMember = "BranchName";
                cmbBranchItems.ValueMember = "BranchID";

                ClearBelowItemDescription();

                dgItems.DataSource = null;
                tabControl1.SelectTab(3);

                cmbBranchItems.SelectedIndex = 0;
                txtItemModify.Clear();
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void ClearBelowItemDescription()
        {
            txtItemName.Clear();
            txtItemCode.Clear();
            if (cmbDepartments.Items.Count > 0)
                cmbDepartments.SelectedIndex = 0;
            txtPrice.Clear();
            if (cmbGroup.Items.Count > 0)
                cmbGroup.SelectedIndex = 0;
            if (cmbNegativeStock.Items.Count > 0)
                cmbNegativeStock.SelectedIndex = 0;
            if (cmbAcceptDecimalQty.Items.Count > 0)
                cmbAcceptDecimalQty.SelectedIndex = 0;
            txtPopupLimit.Clear();
            if (cmbShowInBilling.Items.Count > 0)
                cmbShowInBilling.SelectedIndex = 0;
        }

        private void btnGetItems_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                isNewItem = false;
                ClearBelowItemDescription();
                PopulateValues();
                dgItems.DataSource = DBHelper.GetItemsByBranch(cmbBranchItems.SelectedValue.ToString(), txtItemModify.Text);

                if (dgItems.Rows.Count > 0)
                {
                    dgItems.Columns[0].Width = 50;
                    //dgItems.Columns[0].ReadOnly = true;

                    dgItems.Columns[1].Width = 220;
                    //dgItems.Columns[1].ReadOnly = true;

                    dgItems.Columns[2].Visible = false;
                    //dgItems.Columns[3].ReadOnly = true;
                    dgItems.Columns[3].Width = 120;

                    dgItems.Columns[4].Width = 60;
                    dgItems.Columns[4].HeaderText = "Cost Price";

                    dgItems.Columns[5].Width = 60;
                    dgItems.Columns[5].HeaderText = "Selling Price";

                    dgItems.Columns[6].Width = 60;
                    dgItems.Columns[6].HeaderText = "-ve Stock";

                    dgItems.Columns[7].Width = 60;
                    dgItems.Columns[7].HeaderText = "Decimal";

                    dgItems.Columns[8].Width = 70;
                    dgItems.Columns[8].HeaderText = "Popup Limit";

                    dgItems.Columns[9].Width = 70;
                    dgItems.Columns[9].HeaderText = "Show In Billing";

                    dgItems.Columns[10].Width = 60;
                    dgItems.Columns[10].HeaderText = "Group";

                    dgItems.Columns[11].Visible = false;

                    dgItems.Columns[12].Visible = false;

                    dgItems.Columns[13].Visible = false;

                    dgItems.Focus();
                    Cursor.Current = Cursors.Default;
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdateItems_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (cmbBranchItems.SelectedValue.ToString() == "0" || cmbBranchItems.SelectedValue.ToString() == "-1" || cmbBranchItems.SelectedValue.ToString() == "-2")
                {
                    if (isNewItem)
                    {
                        int isExist = DBHelper.GetItemWhetherExists(cmbBranchItems.SelectedValue.ToString(), txtItemCode.Text, txtItemName.Text);
                        Cursor.Current = Cursors.Default;
                        if (isExist == -1)
                        {
                            MessageBox.Show("Item Code Already Exists!", "Invalid Item Code", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            return;
                        }
                        else if (isExist == -2)
                        {
                            MessageBox.Show("Item Name Already Exists!", "Invalid Item Name", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                            return;
                        }
                    }

                    if (DBHelper.UpdateItem(cmbBranchItems.SelectedValue.ToString(), txtItemCode.Text, txtItemName.Text, int.Parse(cmbDepartments.SelectedValue.ToString()), double.Parse(txtPrice.Text), bool.Parse(cmbNegativeStock.Text.ToLower()), bool.Parse(cmbAcceptDecimalQty.Text.ToLower()), double.Parse(txtPopupLimit.Text), bool.Parse(cmbShowInBilling.Text.ToLower()), int.Parse(cmbGroup.Text), bool.Parse(cmbMfgVisible.Text.ToLower()), cmbSection.SelectedValue.ToString(), bool.Parse(cmbPerishable.Text.ToLower())) > 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Added / Updated Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnGetItems_Click(sender, e);
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error Has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    if (DialogResult.OK == MessageBox.Show("Only Group will be updated at " + cmbBranchItems.Text + " Branch. Do you want to proceed?", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        if (DBHelper.UpdateBranchItem(cmbBranchItems.SelectedValue.ToString(), txtItemCode.Text, int.Parse(cmbGroup.Text)) > 0)
                        {
                            Cursor.Current = Cursors.Default;
                            MessageBox.Show("Item Updated Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            btnGetItems_Click(sender, e);
                        }
                        else
                        {
                            Cursor.Current = Cursors.Default;
                            MessageBox.Show("Some Unknown Error Has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                Cursor.Current = Cursors.Default;
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgItems_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgItems.SelectedRows.Count > 0)
                {
                    DataGridViewRow row = dgItems.SelectedRows[0];

                    txtItemCode.Text = row.Cells[0].Value.ToString();
                    txtItemCode.Enabled = false;

                    txtItemName.Text = row.Cells[1].Value.ToString();
                    txtItemName.Enabled = false;

                    cmbDepartments.SelectedValue = row.Cells[2].Value.ToString();

                    txtPrice.Text = row.Cells[5].Value.ToString();

                    cmbGroup.SelectedIndex = int.Parse(row.Cells[10].Value.ToString()) - 1;

                    if ((bool)row.Cells[6].Value)
                        cmbNegativeStock.SelectedIndex = 0;
                    else
                        cmbNegativeStock.SelectedIndex = 1;

                    if ((bool)row.Cells[7].Value)
                        cmbAcceptDecimalQty.SelectedIndex = 0;
                    else
                        cmbAcceptDecimalQty.SelectedIndex = 1;

                    txtPopupLimit.Text = row.Cells[8].Value.ToString();

                    if ((bool)row.Cells[9].Value)
                        cmbShowInBilling.SelectedIndex = 0;
                    else
                        cmbShowInBilling.SelectedIndex = 1;

                    if ((bool)row.Cells[11].Value)
                        cmbMfgVisible.SelectedIndex = 0;
                    else
                        cmbMfgVisible.SelectedIndex = 1;

                    cmbSection.SelectedValue = row.Cells[12].Value;

                    if ((bool)row.Cells[13].Value)
                        cmbPerishable.SelectedIndex = 0;
                    else
                        cmbPerishable.SelectedIndex = 1;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void PopulateValues()
        {
            try
            {
                if (cmbDepartments.Items.Count <= 0)
                {
                    cmbDepartments.DataSource = DBHelper.GetDepartments(cmbBranchItems.SelectedValue.ToString());
                    cmbDepartments.DisplayMember = "Department";
                    cmbDepartments.ValueMember = "DeptID";
                }

                if (cmbGroup.Items.Count <= 0)
                {
                    cmbGroup.Items.Add("1");
                    cmbGroup.Items.Add("2");
                    cmbGroup.Items.Add("3");
                    cmbGroup.Items.Add("4");
                }
                cmbGroup.SelectedIndex = 0;

                if (cmbNegativeStock.Items.Count <= 0)
                {
                    cmbNegativeStock.Items.Add("True");
                    cmbNegativeStock.Items.Add("False");
                }
                cmbNegativeStock.SelectedIndex = 0;

                if (cmbAcceptDecimalQty.Items.Count <= 0)
                {
                    cmbAcceptDecimalQty.Items.Add("True");
                    cmbAcceptDecimalQty.Items.Add("False");
                }
                cmbAcceptDecimalQty.SelectedIndex = 0;

                if (cmbShowInBilling.Items.Count <= 0)
                {
                    cmbShowInBilling.Items.Add("True");
                    cmbShowInBilling.Items.Add("False");
                }
                cmbShowInBilling.SelectedIndex = 0;

                if (cmbSection.Items.Count <= 0)
                {
                    cmbSection.DataSource = DBHelper.GetSectionsFromStockManagement();
                    cmbSection.DisplayMember = "SectionName";
                    cmbSection.ValueMember = "SectionID";
                }

                cmbSection.SelectedIndex = 0;

                if (cmbPerishable.Items.Count <= 0)
                {
                    cmbPerishable.Items.Add("True");
                    cmbPerishable.Items.Add("False");
                }
                cmbPerishable.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddNewItem_Click(object sender, EventArgs e)
        {
            try
            {
                isNewItem = true;

                PopulateValues();

                dgItems.DataSource = null;

                txtItemName.Clear();
                txtItemName.Enabled = true;

                txtItemCode.Clear();
                txtItemCode.Enabled = true;

                txtPrice.Clear();
                if (cmbDepartments.Items.Count > 0)
                    cmbDepartments.SelectedIndex = 0;
                else
                {

                }
                if (cmbGroup.Items.Count > 0)
                    cmbGroup.SelectedIndex = 0;
                if (cmbAcceptDecimalQty.Items.Count > 0)
                    cmbAcceptDecimalQty.SelectedIndex = 0;
                if (cmbNegativeStock.Items.Count > 0)
                    cmbNegativeStock.SelectedIndex = 0;
                if (cmbShowInBilling.Items.Count > 0)
                    cmbShowInBilling.SelectedIndex = 0;
                txtPopupLimit.Clear();
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtItemCode_TextChanged(object sender, EventArgs e)
        {
            if (!txtItemCode.ReadOnly)
            {
                int temp;
                if (!(int.TryParse(txtItemCode.Text, out temp)))
                {
                    txtItemCode.Clear();
                }
            }
        }

        private void txtPrice_TextChanged(object sender, EventArgs e)
        {
            if (!txtPrice.ReadOnly)
            {
                double temp;
                if (!(double.TryParse(txtPrice.Text, out temp)))
                {
                    txtPrice.Clear();
                }
            }
        }

        private void txtPopupLimit_TextChanged(object sender, EventArgs e)
        {
            if (!txtPopupLimit.ReadOnly)
            {
                int temp;
                if (!(int.TryParse(txtPopupLimit.Text, out temp)))
                {
                    txtPopupLimit.Clear();
                }
            }
        }

        private void cmbBranchItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranchItems.SelectedValue != null)
            {
                if (cmbBranchItems.SelectedValue.ToString() == "0" || cmbBranchItems.SelectedValue.ToString() == "-1" || cmbBranchItems.SelectedValue.ToString() == "-2")
                {
                    btnSyncItems.Enabled = false;
                    btnAddNewItem.Enabled = true;
                    btnUpdateItems.Text = "Add/Update Item";
                }
                else
                {
                    btnSyncItems.Enabled = true;
                    btnAddNewItem.Enabled = false;
                    btnUpdateItems.Text = "Update Item";
                }
            }
        }

        private void btnSyncItems_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to sync items at " + cmbBranchItems.Text + " Branch?", "Confirm Sync", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.SyncMasterItems(cmbBranchItems.SelectedValue.ToString()) == 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Master Items Synced Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgItems.DataSource = null;
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Edit Amounts

        private void btnEditAmounts_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (BranchesData == null)
                        BranchesData = DBHelper.GetBranches();
                    cmbBranchesAmounts.DataSource = BranchesData;
                    cmbBranchesAmounts.DisplayMember = "BranchName";
                    cmbBranchesAmounts.ValueMember = "BranchID";
                    //dgEditAmounts.DataSource = null;
                    tabControl1.SelectTab(4);
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnGetAmountDetails_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                dtDateSelected = dpEditAmounts.Value;
                branchSelected = cmbBranchesAmounts.SelectedValue.ToString();
                isBranchSelected = chkBranchConnect.Checked;

                dgvAmounts.DataSource = DBHelper.GetAmountsByBranch(dpEditAmounts.Value, cmbBranchesAmounts.SelectedValue.ToString(), chkBranchConnect.Checked);
                Cursor.Current = Cursors.Default;
                if (dgvAmounts.DataSource != null)
                    dgvAmounts.Columns[0].Visible = false;
                else
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //if (dt != null)
                //{
                //    txtSodexho.Text = dt.Rows[0]["Sodexho"].ToString();
                //    txtCreditCard.Text = dt.Rows[0]["CreditCard"].ToString();
                //}
                //else
                //{
                //    txtSodexho.Text = string.Empty;
                //    txtCreditCard.Text = string.Empty;
                //    MessageBox.Show("No Data Available !!!", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //}
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdateAmounts_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                string id = "0";
                if (dgvAmounts != null && dgvAmounts.SelectedRows.Count > 0)
                    id = dgvAmounts.SelectedRows[0].Cells[0].Value.ToString();

                if (DBHelper.UpdateAmounts(id, txtSodexho.Text, txtCreditCard.Text, dtDateSelected, branchSelected, isBranchSelected, txtCashier.Text) > 0)
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Updated Amounts Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //txtSodexho.Clear();
                    //txtCreditCard.Clear();
                    btnGetAmountDetails_Click(sender, e);
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Some Error Has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtSodexho_TextChanged(object sender, EventArgs e)
        {
            if (!txtSodexho.ReadOnly)
            {
                double temp;
                if (!(double.TryParse(txtSodexho.Text, out temp)))
                {
                    txtSodexho.Clear();
                }
            }
        }

        private void txtCreditCard_TextChanged(object sender, EventArgs e)
        {
            if (!txtCreditCard.ReadOnly)
            {
                double temp;
                if (!(double.TryParse(txtCreditCard.Text, out temp)))
                {
                    txtCreditCard.Clear();
                }
            }
        }

        private void dgvAmounts_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgvAmounts != null && dgvAmounts.SelectedRows.Count > 0)
                {
                    txtSodexho.Text = dgvAmounts.SelectedRows[0].Cells[1].Value.ToString();
                    txtCreditCard.Text = dgvAmounts.SelectedRows[0].Cells[2].Value.ToString();
                    txtCashier.Text = dgvAmounts.SelectedRows[0].Cells[3].Value.ToString();
                }
            }
            catch (Exception)
            { }
        }

        private void btnAddNewAmount_Click(object sender, EventArgs e)
        {
            try
            {
                dgvAmounts.DataSource = null;
                txtSodexho.Clear();
                txtCreditCard.Clear();
                txtCashier.Clear();
            }
            catch (Exception) { }
        }

        #endregion

        #region Edit Expenses

        private void btnExpensesMove_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    if (BranchesData == null)
                        BranchesData = DBHelper.GetBranches();
                    cmbExpenseBranch.DataSource = BranchesData;
                    cmbExpenseBranch.DisplayMember = "BranchName";
                    cmbExpenseBranch.ValueMember = "BranchID";
                    btnUpdateExpense.Enabled = false;
                    dgExpenses.DataSource = null;
                    tabControl1.SelectTab(5);
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnGetExpenses_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                dtDateSelected = dpExpense.Value;
                branchSelected = cmbExpenseBranch.SelectedValue.ToString();
                isBranchSelected = chkBranchConnectExpenses.Checked;

                cmbExpenses.DataSource = null;
                txtExpenseAmt.Clear();
                txtExpenseDesc.Clear();
                txtExpCashier.Clear();
                btnUpdateExpense.Enabled = false;

                dgExpenses.DataSource = null;
                DataTable dt = DBHelper.GetExpensesByBranch(dtDateSelected, branchSelected, isBranchSelected);
                if (dt != null)
                {
                    cmbExpenses.DataSource = DBHelper.GetExpenseItemsByBranch(branchSelected, isBranchSelected);
                    cmbExpenses.DisplayMember = "ExpenseItem";
                    cmbExpenses.ValueMember = "ID";

                    dgExpenses.DataSource = dt;
                    dgExpenses.Columns[0].Width = 80;
                    dgExpenses.Columns[1].Visible = false;
                    dgExpenses.Columns[2].Width = 200;
                    dgExpenses.Columns[3].Width = 100;
                    dgExpenses.Columns[4].Width = 100;
                    dgExpenses.Columns[5].Width = 315;

                    btnUpdateExpense.Enabled = true;
                    Cursor.Current = Cursors.Default;
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Data Not Available !!!", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgExpenses_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgExpenses.SelectedRows.Count > 0)
                {
                    cmbExpenses.SelectedValue = dgExpenses.SelectedRows[0].Cells[1].Value.ToString();
                    txtExpenseAmt.Text = dgExpenses.SelectedRows[0].Cells[3].Value.ToString();
                    txtExpCashier.Text = dgExpenses.SelectedRows[0].Cells[4].Value.ToString();
                    txtExpenseDesc.Text = dgExpenses.SelectedRows[0].Cells[5].Value.ToString();
                }
            }
            catch (Exception)
            { }
        }

        private void btnUpdateExpense_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtExpenseAmt.Text.Trim() == string.Empty)
                {
                    MessageBox.Show("Please enter valid Amount", "Invalid Amount", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtExpenseAmt.Focus();
                    return;
                }
                Cursor.Current = Cursors.WaitCursor;
                int isUpdated = 0;

                if (dgExpenses.DataSource != null)
                {
                    isUpdated = DBHelper.UpdateExpense(dgExpenses.SelectedRows[0].Cells[0].Value.ToString(), cmbExpenses.SelectedValue.ToString(), txtExpenseAmt.Text, txtExpenseDesc.Text, branchSelected, isBranchSelected, dpExpense.Value, txtExpCashier.Text);
                }
                else
                {
                    isUpdated = DBHelper.UpdateExpense("0", cmbExpenses.SelectedValue.ToString(), txtExpenseAmt.Text, txtExpenseDesc.Text, branchSelected, isBranchSelected, dpExpense.Value, txtExpCashier.Text);
                }
                Cursor.Current = Cursors.Default;
                if (isUpdated > 0)
                {
                    MessageBox.Show("Expense Updated Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cmbExpenses.DataSource = null;
                    txtExpenseAmt.Clear();
                    txtExpenseDesc.Clear();
                }
                else
                {
                    MessageBox.Show("Some Error Has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                btnGetExpenses_Click(sender, e);
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtExpenseAmt_TextChanged(object sender, EventArgs e)
        {
            double temp;
            if (!(double.TryParse(txtExpenseAmt.Text, out temp)))
            {
                txtExpenseAmt.Clear();
            }
        }

        private void btnPrepareAddNew_Click(object sender, EventArgs e)
        {
            dgExpenses.DataSource = null;
            cmbExpenses.DataSource = DBHelper.GetExpenseItemsByBranch(branchSelected, isBranchSelected);
            cmbExpenses.DisplayMember = "ExpenseItem";
            cmbExpenses.ValueMember = "ID";
            txtExpenseAmt.Clear();
            txtExpenseDesc.Clear();
            txtExpCashier.Clear();
            btnUpdateExpense.Enabled = true;
        }

        #endregion

        #region View/Cancel Bill

        private void btnBillCancel_Click(object sender, EventArgs e)
        {
            try
            {
                dgBills.DataSource = null;
                dgBillDetails.DataSource = null;

                if (BranchesData == null)
                    BranchesData = DBHelper.GetBranches();
                cmbBillBranch.DataSource = BranchesData;
                cmbBillBranch.DisplayMember = "BranchName";
                cmbBillBranch.ValueMember = "BranchID";
                tabControl1.SelectTab(6);
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancelBill_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                dtDateSelected = dpBillDate.Value;
                branchSelected = cmbBillBranch.SelectedValue.ToString();
                //isBranchSelected = chkBranchConnectBill.Checked;
                isBranchSelected = false;

                dgBills.DataSource = null;
                DataTable dt = DBHelper.GetBillsByBranch(dtDateSelected, branchSelected, isBranchSelected);
                Cursor.Current = Cursors.Default;
                if (dt != null)
                {
                    dgBills.DataSource = dt;
                    dgBills.Columns[5].Visible = false;
                    dgBills.Columns[6].Visible = false;
                }
                else
                {
                    MessageBox.Show("No Data Available !!!", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgBills_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgBills.SelectedRows.Count > 0)
                {
                    dgBillDetails.DataSource = DBHelper.GetBillDetails(DateTime.Parse(dgBills.SelectedRows[0].Cells[5].Value.ToString()), dgBills.SelectedRows[0].Cells[0].Value.ToString(), dgBills.SelectedRows[0].Cells[6].Value.ToString());
                    dgBillDetails.Columns[2].Width = 200;

                    txtBillNo.Text = dgBills.SelectedRows[0].Cells[0].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnUpdateBill_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                int result = DBHelper.CancelBill(txtBillNo.Text.Trim(), txtCancelledReason.Text.Trim(), branchSelected, isBranchSelected);

                Cursor.Current = Cursors.Default;
                if (result > 0)
                {
                    MessageBox.Show("Bill Cancelled Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //dgBills.DataSource = null;
                    txtBillNo.Clear();
                    txtCancelledReason.Clear();
                    btnCancelBill_Click(sender, e);
                    return;
                }
                else
                {
                    MessageBox.Show("Some Error Has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region View/Cancel Cake

        private void btnCakeShow_Click(object sender, EventArgs e)
        {
            try
            {
                dgCancelCakes.DataSource = null;
                txtCakeBillNo.Clear();
                chkCancelCakeBranchConnect.Checked = true;
                if (BranchesData == null)
                    BranchesData = DBHelper.GetBranches();
                cmbCancelCakeBranches.DataSource = BranchesData;
                cmbCancelCakeBranches.DisplayMember = "BranchName";
                cmbCancelCakeBranches.ValueMember = "BranchID";
                tabControl1.SelectTab(7);
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGetCakes_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                dtDateSelected = dpCancelCake.Value;
                branchSelected = cmbCancelCakeBranches.SelectedValue.ToString();
                //isBranchSelected = chkCancelCakeBranchConnect.Checked;
                isBranchSelected = false;

                dgCancelCakes.DataSource = null;
                DataTable dt = DBHelper.GetCakesByBranch(dtDateSelected, branchSelected, isBranchSelected);
                Cursor.Current = Cursors.Default;
                if (dt != null)
                {
                    dgCancelCakes.DataSource = dt;
                    dgCancelCakes.Columns[8].Width = 200;
                }
                else
                {
                    MessageBox.Show("No Data Available !!!", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgCancelCakes_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgCancelCakes.SelectedRows.Count > 0)
                {
                    txtCakeBillNo.Text = dgCancelCakes.SelectedRows[0].Cells[0].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancelCake_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                int result = DBHelper.CancelCakeBill(txtCakeBillNo.Text.Trim(), branchSelected, isBranchSelected);
                Cursor.Current = Cursors.Default;
                if (result > 0)
                {
                    MessageBox.Show("Cake Cancelled Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtCakeBillNo.Clear();
                    btnGetCakes_Click(sender, e);
                    return;
                }
                else
                {
                    MessageBox.Show("Some Error Has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Manage Billing Login

        private void btnBillingLogin_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgManageLogin.DataSource = null;
                    if (BranchesData == null)
                        BranchesData = DBHelper.GetBranches();
                    cmbLoginBranches.DataSource = BranchesData;
                    cmbLoginBranches.DisplayMember = "BranchName";
                    cmbLoginBranches.ValueMember = "BranchID";

                    branchSelected = cmbLoginBranches.SelectedValue.ToString();

                    cmbEmployees.DataSource = DBHelper.GetEmployeesByBranch(cmbLoginBranches.SelectedValue.ToString());
                    cmbEmployees.DisplayMember = "EmpName";
                    cmbEmployees.ValueMember = "EmpID";

                    tabControl1.SelectTab(8);
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnGetUserDetails_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbLoginBranches.SelectedValue.ToString();

                dgManageLogin.DataSource = DBHelper.GetAllLoginsByBranch(branchSelected);

                Cursor.Current = Cursors.Default;
                if (dgManageLogin.DataSource == null)
                {
                    MessageBox.Show("No Logins Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    dgManageLogin.Columns[0].Width = 50;
                    dgManageLogin.Columns[1].Width = 210;
                    dgManageLogin.Columns[2].Width = 200;
                    dgManageLogin.Columns[3].Width = 150;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (dgManageLogin.SelectedRows.Count > 0)
                {
                    if (DialogResult.OK == MessageBox.Show("Do You Want to Delete the \"" + dgManageLogin.SelectedRows[0].Cells[1].Value.ToString() + "\" User", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                    {
                        int result = DBHelper.DeleteUser(dgManageLogin.SelectedRows[0].Cells[0].Value.ToString(), dgManageLogin.SelectedRows[0].Cells[2].Value.ToString(), dgManageLogin.SelectedRows[0].Cells[2].Value.ToString(), branchSelected);
                        Cursor.Current = Cursors.Default;
                        if (result > 0)
                        {
                            MessageBox.Show("User Details Successfully Deleted", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            txtUser.Clear();
                            txtPwd.Clear();
                            dgManageLogin.DataSource = DBHelper.GetAllLoginsByBranch(branchSelected);
                            return;
                        }
                        else
                        {
                            MessageBox.Show("Some Error Has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Select the User in the Grid to proceed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddNewUser_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (txtUser.Text.Trim() != string.Empty && txtPwd.Text.Trim() != string.Empty)
                {
                    int result = DBHelper.AddUser(cmbEmployees.SelectedValue.ToString(), txtUser.Text.Trim(), txtPwd.Text.Trim(), branchSelected);

                    Cursor.Current = Cursors.Default;
                    if (result > 0)
                    {
                        MessageBox.Show("User Details Successfully Created", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtUser.Clear();
                        txtPwd.Clear();
                        btnGetUserDetails_Click(sender, e);
                        return;
                    }
                    else if (result == -1)
                    {
                        MessageBox.Show("User Name already existing. Please user different UserName", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtUser.Clear();
                        return;
                    }
                    else
                    {
                        MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Please fill both User Name & Password", "Invalid Details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cmbLoginBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (cmbLoginBranches.SelectedValue != null && cmbLoginBranches.Text != string.Empty)
                {
                    branchSelected = cmbLoginBranches.SelectedValue.ToString();

                    cmbEmployees.DataSource = DBHelper.GetEmployeesByBranch(cmbLoginBranches.SelectedValue.ToString());
                    cmbEmployees.DisplayMember = "EmpName";
                    cmbEmployees.ValueMember = "EmpID";
                }

                txtUser.Clear();
                txtPwd.Clear();

                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Manage Cake Flavours

        private void btnCakeFlavoursModify_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    cmbBranchCakeFlavours.DataSource = null;
                    DataTable dt = new DataTable();
                    dt.Columns.Add("BranchID");
                    dt.Columns.Add("BranchName");

                    //DataTable dt = DBHelper.GetBranches();
                    dt.Rows.Add(0, "Central Branches");
                    //dt.Rows.Add(-1, "Central CSC");
                    dt.Rows.Add(-2, "Central Sangareddy");
                    cmbBranchCakeFlavours.DataSource = dt;
                    cmbBranchCakeFlavours.DisplayMember = "BranchName";
                    cmbBranchCakeFlavours.ValueMember = "BranchID";
                    tabControl1.SelectTab(9);
                    txtCakeFlavour.Enabled = false;
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnGetAllCakeFlavours_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbBranchCakeFlavours.SelectedValue.ToString();

                txtCakeFlavour.Enabled = false;
                dgCakeFlavours.DataSource = DBHelper.GetAllCakeFlavoursByBranch(branchSelected);
                Cursor.Current = Cursors.Default;
                if (dgCakeFlavours.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtCakeFlavour.Clear();
                    txtCakeFlavourPrice.Clear();
                    return;
                }
                else
                {
                    dgCakeFlavours.Columns[0].Visible = false;
                    dgCakeFlavours.Columns[1].Width = 250;
                    dgCakeFlavours.Columns[2].Width = 100;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgCakeFlavours_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgCakeFlavours.SelectedRows.Count > 0)
                {
                    txtCakeFlavour.Text = dgCakeFlavours.SelectedRows[0].Cells[1].Value.ToString();
                    txtCakeFlavourPrice.Text = dgCakeFlavours.SelectedRows[0].Cells[2].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtCakeFlavourPrice_TextChanged(object sender, EventArgs e)
        {
            if (!txtCakeFlavourPrice.ReadOnly)
            {
                double temp;
                if (!(double.TryParse(txtCakeFlavourPrice.Text, out temp)))
                {
                    txtCakeFlavourPrice.Clear();
                }
            }
        }

        private void btnAddUpdateFlavour_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (txtCakeFlavour.Text.Trim() != string.Empty && txtCakeFlavourPrice.Text.Trim() != string.Empty)
                {
                    int result = 0;
                    if (txtCakeFlavour.Enabled)
                    {
                        //Add New Flavour
                        result = DBHelper.AddOrUpdateCakeFlavour("0", txtCakeFlavour.Text, txtCakeFlavourPrice.Text, cmbBranchCakeFlavours.SelectedValue.ToString());
                    }
                    else
                    {
                        //Edit Old Flavour
                        result = DBHelper.AddOrUpdateCakeFlavour(dgCakeFlavours.SelectedRows[0].Cells[0].Value.ToString(), txtCakeFlavour.Text, txtCakeFlavourPrice.Text, cmbBranchCakeFlavours.SelectedValue.ToString());
                    }

                    Cursor.Current = Cursors.Default;
                    if (result > 0)
                    {
                        MessageBox.Show("Cake Flavour Added/Updated Successfully", "Cake Flavour Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtCakeFlavour.Clear();
                        txtCakeFlavourPrice.Clear();
                        btnGetAllCakeFlavours_Click(sender, e);
                    }
                    else if (result == -1)
                    {
                        MessageBox.Show("Cake Flavour Added Exists", "Cake Flavour Added", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Please fill both Cake Flavour & Price/KG", "Invalid Details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cmbBranchCakeFlavours_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranchCakeFlavours.SelectedValue != null)
            {
                if (cmbBranchCakeFlavours.SelectedValue.ToString() == "0" || cmbBranchCakeFlavours.SelectedValue.ToString() == "-1" || cmbBranchCakeFlavours.SelectedValue.ToString() == "-2")
                {
                    btnSyncFlavours.Enabled = false;
                    btnAddUpdateFlavour.Enabled = true;
                }
                else
                {
                    btnSyncFlavours.Enabled = true;
                    btnAddUpdateFlavour.Enabled = false;
                }
            }
        }

        private void btnPrepareNew_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbBranchCakeFlavours.SelectedValue != null)
                {
                    if (cmbBranchCakeFlavours.SelectedValue.ToString() == "0" || cmbBranchCakeFlavours.SelectedValue.ToString() == "-1" || cmbBranchCakeFlavours.SelectedValue.ToString() == "-2")
                    {
                        dgCakeFlavours.DataSource = null;
                        txtCakeFlavour.Clear();
                        txtCakeFlavourPrice.Clear();
                        btnAddUpdateFlavour.Enabled = txtCakeFlavour.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("Please Select Central in the Branch Drop Down", "Select Central Branch", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSyncFlavours_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to Sync Cake Flavours in " + cmbBranchCakeFlavours.Text + " Branch?", "Sync Cake Flavours", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.SyncCakeFlavoursByBranch(cmbBranchCakeFlavours.SelectedValue.ToString()) == 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Cake Flavours Synced Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgCakeFlavours.DataSource = null;
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Manage Cake Shapes

        private void btnCakeShapes_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgCakeShapes.DataSource = null;

                    //DataTable dt = DBHelper.GetBranches();

                    DataTable dt = new DataTable();
                    dt.Columns.Add("BranchID");
                    dt.Columns.Add("BranchName");

                    dt.Rows.Add(0, "Central");
                    cmbBranchesCakeShapes.DataSource = dt;
                    cmbBranchesCakeShapes.DisplayMember = "BranchName";
                    cmbBranchesCakeShapes.ValueMember = "BranchID";
                    tabControl1.SelectTab(10);
                    txtShape.Enabled = false;
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnGetAllShapes_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbBranchesCakeShapes.SelectedValue.ToString();

                txtShape.Enabled = false;
                dgCakeShapes.DataSource = DBHelper.GetAllCakeShapesByBranch(branchSelected);
                Cursor.Current = Cursors.Default;

                if (dgCakeShapes.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtShape.Clear();
                    return;
                }
                else
                {
                    dgCakeShapes.Columns[0].Visible = false;
                    dgCakeShapes.Columns[1].Width = 150;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgCakeShapes_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgCakeShapes.SelectedRows.Count > 0)
                {
                    txtShape.Text = dgCakeShapes.SelectedRows[0].Cells[1].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddNewShape_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbBranchesCakeShapes.SelectedValue != null)
                {
                    if (cmbBranchesCakeShapes.SelectedValue.ToString() == "0")
                    {
                        dgCakeShapes.DataSource = null;
                        txtShape.Clear();
                        btnAddShape.Enabled = txtShape.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("Please Select Central in the Branch Drop Down", "Select Central Branch", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddShape_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (txtShape.Text.Trim() != string.Empty)
                {
                    int result = 0;
                    if (txtShape.Enabled)
                    {
                        //Add New Shape
                        result = DBHelper.AddCakeShape("0", txtShape.Text);
                    }
                    Cursor.Current = Cursors.Default;

                    if (result > 0)
                    {
                        MessageBox.Show("Cake Shape Added Successfully", "Cake Shape Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtShape.Clear();
                        btnGetAllShapes_Click(sender, e);
                    }
                    else if (result == -1)
                    {
                        MessageBox.Show("Cake Shape Added Exists", "Cake Shape Added", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Please fill both Cake Flavour & Price/KG", "Invalid Details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cmbBranchesCakeShapes_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranchesCakeShapes.SelectedValue != null)
            {
                if (cmbBranchesCakeShapes.SelectedValue.ToString() == "0")
                {
                    btnSyncShape.Enabled = false;
                    btnAddShape.Enabled = txtShape.Enabled;
                }
                else
                {
                    btnSyncShape.Enabled = true;
                    btnAddShape.Enabled = false;
                }
            }
        }

        private void btnSyncShape_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to Sync Cake Shapes in " + cmbBranchesCakeShapes.Text + " Branch?", "Sync Cake Shapes", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.SyncCakeShapesByBranch(cmbBranchesCakeShapes.SelectedValue.ToString()) == 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Cake Shapes Synced Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgCakeFlavours.DataSource = null;
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Manage Expenses

        private void btnManageExpenses_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgExpenseItems.DataSource = null;

                    //DataTable dt = DBHelper.GetBranches();

                    DataTable dt = new DataTable();
                    dt.Columns.Add("BranchID");
                    dt.Columns.Add("BranchName");

                    dt.Rows.Add(0, "Central");
                    cmbBranchExpenses.DataSource = dt;
                    cmbBranchExpenses.DisplayMember = "BranchName";
                    cmbBranchExpenses.ValueMember = "BranchID";
                    tabControl1.SelectTab(11);
                    txtExpenseItem.Enabled = false;
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnGetAllExpenseItems_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbBranchExpenses.SelectedValue.ToString();

                txtExpenseItem.Enabled = false;
                dgExpenseItems.DataSource = DBHelper.GetAllExpenseItemsByBranch(branchSelected);
                Cursor.Current = Cursors.Default;

                if (dgExpenseItems.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtExpenseItem.Clear();
                    return;
                }
                else
                {
                    dgExpenseItems.Columns[0].Visible = false;
                    dgExpenseItems.Columns[1].Width = 150;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgExpenseItems_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgExpenseItems.SelectedRows.Count > 0)
                {
                    txtExpenseItem.Text = dgExpenseItems.SelectedRows[0].Cells[1].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrepareExpense_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbBranchExpenses.SelectedValue != null)
                {
                    if (cmbBranchExpenses.SelectedValue.ToString() == "0")
                    {
                        dgExpenseItems.DataSource = null;
                        txtExpenseItem.Clear();
                        btnAddExpenseItem.Enabled = txtExpenseItem.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("Please Select Central in the Branch Drop Down", "Select Central Branch", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddExpenseItem_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (txtExpenseItem.Text.Trim() != string.Empty)
                {
                    int result = 0;
                    if (txtExpenseItem.Enabled)
                    {
                        //Add New Expense Item
                        result = DBHelper.AddExpenseItem("0", txtExpenseItem.Text);
                    }
                    Cursor.Current = Cursors.Default;
                    if (result > 0)
                    {
                        MessageBox.Show("Expense Item Added Successfully", "Expense Item Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtExpenseItem.Clear();
                        btnGetAllExpenseItems_Click(sender, e);
                    }
                    else if (result == -1)
                    {
                        MessageBox.Show("Expense Item Already Exists", "Expense Item Exists", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Please fill Expense Item", "Invalid Details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cmbBranchExpenses_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranchExpenses.SelectedValue != null)
            {
                if (cmbBranchExpenses.SelectedValue.ToString() == "0")
                {
                    btnSyncExpenses.Enabled = false;
                    btnAddExpenseItem.Enabled = txtExpenseItem.Enabled;
                }
                else
                {
                    btnSyncExpenses.Enabled = true;
                    btnAddExpenseItem.Enabled = false;
                }
            }
        }

        private void btnSyncExpenses_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to Sync Expense Items in " + cmbBranchExpenses.Text + " Branch?", "Sync Expense Items", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.SyncExpenseItemsByBranch(cmbBranchExpenses.SelectedValue.ToString()) == 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Expense Items Synced Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgExpenseItems.DataSource = null;
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region CreditNote Companies

        private void btnCreditNoteComp_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgCreditCompanies.DataSource = null;

                    DataTable dt = new DataTable();
                    dt.Columns.Add("BranchID");
                    dt.Columns.Add("BranchName");

                    //DataTable dt = DBHelper.GetBranches();
                    dt.Rows.Add(0, "Central");
                    cmbCreditCompBranches.DataSource = dt;
                    cmbCreditCompBranches.DisplayMember = "BranchName";
                    cmbCreditCompBranches.ValueMember = "BranchID";
                    tabControl1.SelectTab(12);
                    txtCreditNoteCompany.Enabled = false;
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnGetCompanies_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbCreditCompBranches.SelectedValue.ToString();

                txtCreditNoteCompany.Enabled = false;
                dgCreditCompanies.DataSource = DBHelper.GetAllCompaniesByBranch(branchSelected);
                Cursor.Current = Cursors.Default;
                if (dgCreditCompanies.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtCreditNoteCompany.Clear();
                    return;
                }
                else
                {
                    dgCreditCompanies.Columns[0].Visible = false;
                    dgCreditCompanies.Columns[1].Width = 300;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgCreditCompanies_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgCreditCompanies.SelectedRows.Count > 0)
                {
                    txtCreditNoteCompany.Text = dgCreditCompanies.SelectedRows[0].Cells[1].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPrepareNewCompany_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbCreditCompBranches.SelectedValue != null)
                {
                    if (cmbCreditCompBranches.SelectedValue.ToString() == "0")
                    {
                        dgCreditCompanies.DataSource = null;
                        txtCreditNoteCompany.Clear();
                        btnAddCreditNoteCompany.Enabled = txtCreditNoteCompany.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("Please Select Central in the Branch Drop Down", "Select Central Branch", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddCreditNoteCompany_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (txtCreditNoteCompany.Text.Trim() != string.Empty)
                {
                    int result = 0;
                    if (txtCreditNoteCompany.Enabled)
                    {
                        //Add New Expense Item
                        result = DBHelper.AddCreditNoteCompany("0", txtCreditNoteCompany.Text);
                    }
                    Cursor.Current = Cursors.Default;
                    if (result > 0)
                    {
                        MessageBox.Show("Credit Note Company Successfully", "Credit Note Company Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtCreditNoteCompany.Clear();
                        btnGetCompanies_Click(sender, e);
                    }
                    else if (result == -1)
                    {
                        MessageBox.Show("Credit Note Company Already Exists", "Credit Note Company Exists", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show("Please fill Credit Note Company", "Invalid Details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cmbCreditCompBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCreditCompBranches.SelectedValue != null)
            {
                if (cmbCreditCompBranches.SelectedValue.ToString() == "0")
                {
                    btnSyncCompanies.Enabled = false;
                    btnAddCreditNoteCompany.Enabled = txtCreditNoteCompany.Enabled;
                }
                else
                {
                    btnSyncCompanies.Enabled = true;
                    btnAddCreditNoteCompany.Enabled = false;
                }
            }
        }

        private void btnSyncCompanies_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to Sync Credit Note Companies in " + cmbCreditCompBranches.Text + " Branch?", "Sync Credit Note Companies", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.SyncCreditNoteCompaniesByBranch(cmbCreditCompBranches.SelectedValue.ToString()) == 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Credit Note Companies Synced Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgCreditCompanies.DataSource = null;
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Credit Note Company Rates

        private void btnCreditRates_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgRates.DataSource = null;

                    //DataTable dt = DBHelper.GetBranches();

                    DataTable dt = new DataTable();
                    dt.Columns.Add("BranchID");
                    dt.Columns.Add("BranchName");

                    dt.Rows.Add(0, "Central");
                    cmbCreditRatesBranches.DataSource = dt;
                    cmbCreditRatesBranches.DisplayMember = "BranchName";
                    cmbCreditRatesBranches.ValueMember = "BranchID";
                    cmbCreditRatesBranches.SelectedIndex = 0;
                    tabControl1.SelectTab(13);

                    btnSyncRates.Enabled = false;
                    btnUpdateRates.Enabled = false;

                    int sample;
                    if (cmbCreditRatesBranches.SelectedIndex > -1 && int.TryParse(cmbCreditRatesBranches.SelectedValue.ToString(), out sample))
                    {
                        cmbCompany.DataSource = null;
                        cmbCompany.DataSource = DBHelper.GetAllCompaniesByBranch(cmbCreditRatesBranches.SelectedValue.ToString());
                        cmbCompany.DisplayMember = "CreditNoteCompany";
                        cmbCompany.ValueMember = "ID";

                        if (cmbCreditRatesBranches.Text == "Central")
                        {
                            btnSyncRates.Enabled = false;
                            btnUpdateRates.Enabled = true;
                        }
                        else
                        {
                            btnSyncRates.Enabled = true;
                            btnUpdateRates.Enabled = false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        //private void cmbCreditRatesBranches_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        btnSyncRates.Enabled = false;
        //        btnUpdateRates.Enabled = false;

        //        int sample;
        //        if (cmbCreditRatesBranches.SelectedIndex > -1 && int.TryParse(cmbCreditRatesBranches.SelectedValue.ToString(), out sample))
        //        {
        //            cmbCompany.DataSource = null;
        //            cmbCompany.DataSource = DBHelper.GetAllCompaniesByBranch(cmbCreditRatesBranches.SelectedValue.ToString());
        //            cmbCompany.DisplayMember = "CreditNoteCompany";
        //            cmbCompany.ValueMember = "ID";

        //            if (cmbCreditRatesBranches.Text == "Central")
        //            {
        //                btnSyncRates.Enabled = false;
        //                btnUpdateRates.Enabled = true;
        //            }
        //            else
        //            {
        //                btnSyncRates.Enabled = true;
        //                btnUpdateRates.Enabled = false;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WriteToEventViewer(ex.Message);
        //        MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }
        //}

        private void btnGetRates_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbCreditRatesBranches.SelectedValue.ToString();
                dgRates.DataSource = DBHelper.GetCreditNoteRatesByBranchAndCompany(branchSelected, cmbCompany.SelectedValue.ToString());
                Cursor.Current = Cursors.Default;
                if (dgRates.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    dgRates.Columns[0].Width = 100;
                    dgRates.Columns[0].ReadOnly = true;
                    dgRates.Columns[1].Width = 300;
                    dgRates.Columns[1].ReadOnly = true;
                    dgRates.Columns[2].Visible = false;
                    dgRates.Columns[2].ReadOnly = true;
                    dgRates.Columns[3].ReadOnly = false;
                    dgRates.Focus();
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgRates_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (dgRates.SelectedRows.Count > 0)
                {
                    dgRates.SelectedRows[0].Cells[3].Selected = true;
                    if (e.KeyChar > 47 && e.KeyChar < 58)
                    {
                        dgRates.SelectedRows[0].Cells[3].Value = double.Parse(((char)e.KeyChar).ToString());
                        dgRates.BeginEdit(false);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgRates_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string value = dgRates[e.ColumnIndex, e.RowIndex].Value.ToString();

                float result = 0;
                float.TryParse(value, out result);
                if (result < 0)
                {
                    dgRates[e.ColumnIndex, e.RowIndex].Value = 0;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgRates_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void btnUpdateRates_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                double price = 0.0;
                List<CompanyRateItem> items = new List<CompanyRateItem>();
                foreach (DataGridViewRow row in dgRates.Rows)
                {
                    price = double.Parse(row.Cells[3].Value.ToString());
                    if (price != 0)
                    {
                        items.Add(new CompanyRateItem { ItemCode = int.Parse(row.Cells[0].Value.ToString()), Price = price });
                    }
                }

                int result = DBHelper.UpdateCreditNoteRates(cmbCompany.SelectedValue.ToString(), items);
                Cursor.Current = Cursors.Default;
                if (result > 0)
                {
                    MessageBox.Show("Credit Note Rates Updated Successfully", "Credit Note Rates Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dgRates.DataSource = null;
                }
                else
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSyncRates_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to Sync Credit Note Rates in " + cmbCreditRatesBranches.Text + " Branch?", "Sync Credit Note Rates", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.SyncCreditNoteRatesByBranch(cmbCreditRatesBranches.SelectedValue.ToString()) == 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Credit Note Company Rates Synced Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgRates.DataSource = null;
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Vendors

        private void btnVendor_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgVendors.DataSource = null;

                    //DataTable dt = DBHelper.GetBranches();
                    DataTable dt = new DataTable();
                    dt.Columns.Add("BranchID");
                    dt.Columns.Add("BranchName");

                    dt.Rows.Add(0, "Central");
                    cmbBranchVendors.DataSource = dt;
                    cmbBranchVendors.DisplayMember = "BranchName";
                    cmbBranchVendors.ValueMember = "BranchID";
                    tabControl1.SelectTab(14);
                    txtVendor.Enabled = cmbIsValidVendor.Enabled = false;
                    cmbIsValidVendor.SelectedIndex = -1;
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnAllVendors_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbBranchVendors.SelectedValue.ToString();

                txtVendor.Enabled = false;
                cmbIsValidVendor.Enabled = true;
                btnNewVendor.Enabled = true;
                //cmbIsValidVendor.SelectedIndex = -1;
                dgVendors.DataSource = DBHelper.GetAllVendorsByBranch(branchSelected);
                Cursor.Current = Cursors.Default;
                if (dgVendors.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtVendor.Clear();
                    return;
                }
                else
                {
                    dgVendors.Columns[0].Visible = false;
                    dgVendors.Columns[1].Width = 300;
                    dgVendors.Columns[2].Visible = false;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgVendors_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgVendors.SelectedRows.Count > 0)
                {
                    lblVendorID.Text = dgVendors.SelectedRows[0].Cells[0].Value.ToString();
                    txtVendor.Text = dgVendors.SelectedRows[0].Cells[1].Value.ToString();
                    if ((bool)dgVendors.SelectedRows[0].Cells[2].Value)
                        cmbIsValidVendor.SelectedIndex = 0;
                    else
                        cmbIsValidVendor.SelectedIndex = 1;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddNewVendor_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbBranchVendors.SelectedValue != null)
                {
                    if (cmbBranchVendors.SelectedValue.ToString() == "0")
                    {
                        dgVendors.DataSource = null;
                        txtVendor.Clear();
                        lblVendorID.Text = "0";
                        btnNewVendor.Enabled = txtVendor.Enabled = cmbIsValidVendor.Enabled = true;
                        cmbIsValidVendor.SelectedIndex = -1;
                    }
                    else
                    {
                        MessageBox.Show("Please Select Central in the Branch Drop Down", "Select Central Branch", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnNewVendor_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                if (txtVendor.Text.Trim() != string.Empty)
                {
                    int result = DBHelper.AddOrUpdateVendor(lblVendorID.Text, txtVendor.Text, cmbIsValidVendor.SelectedIndex == 0 ? "1" : "0");

                    Cursor.Current = Cursors.Default;
                    if (result > 0)
                    {
                        MessageBox.Show("Vendor Added/Updated Successfully", "Vendor Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtVendor.Clear();
                        btnAllVendors_Click(sender, e);
                    }
                    else if (result == -1)
                    {
                        MessageBox.Show("Vendor Already Exists", "Vendor Exists", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Please fill Vendor", "Invalid Details", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cmbBranchVendors_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranchVendors.SelectedValue != null)
            {
                if (cmbBranchVendors.SelectedValue.ToString() == "0")
                {
                    btnSyncVendors.Enabled = false;
                    btnNewVendor.Enabled = txtVendor.Enabled;
                }
                else
                {
                    btnSyncVendors.Enabled = true;
                    btnNewVendor.Enabled = false;
                }
            }
        }

        private void btnSyncVendors_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to Sync Vendors in " + cmbBranchVendors.Text + " Branch?", "Sync Vendors", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.SyncVendorsByBranch(cmbBranchVendors.SelectedValue.ToString()) == 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Vendors Synced Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgCreditCompanies.DataSource = null;
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Vendor Rates

        private void btnVendorRates_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgVendorRates.DataSource = null;

                    //DataTable dt = DBHelper.GetBranches();

                    DataTable dt = new DataTable();
                    dt.Columns.Add("BranchID");
                    dt.Columns.Add("BranchName");

                    dt.Rows.Add(0, "Central");
                    cmbVendorRatesBranches.DataSource = dt;
                    cmbVendorRatesBranches.DisplayMember = "BranchName";
                    cmbVendorRatesBranches.ValueMember = "BranchID";
                    //cmbVendorRatesBranches.SelectedIndex = 5;
                    tabControl1.SelectTab(15);

                    btnSyncVendorRates.Enabled = false;
                    btnUpdateVendorRates.Enabled = false;

                    if (cmbVendorRatesBranches.SelectedIndex > -1)
                    {
                        cmbVendor.DataSource = null;
                        int sample = 0;
                        if (int.TryParse(cmbVendorRatesBranches.SelectedValue.ToString(), out sample))
                        {
                            cmbVendor.DataSource = DBHelper.GetAllVendorsByBranch(cmbVendorRatesBranches.SelectedValue.ToString());
                            if (cmbVendor.DataSource != null)
                            {
                                cmbVendor.DisplayMember = "Vendor";
                                cmbVendor.ValueMember = "ID";

                                if (cmbVendorRatesBranches.Text == "Central")
                                {
                                    btnSyncVendorRates.Enabled = false;
                                    btnUpdateVendorRates.Enabled = true;
                                    cmbPercent.SelectedIndex = 0;
                                    cmbPercent.Enabled = true;
                                    btnPercentApply.Enabled = true;
                                }
                                else
                                {
                                    btnSyncVendorRates.Enabled = true;
                                    btnUpdateVendorRates.Enabled = false;
                                    cmbPercent.Enabled = false;
                                    btnPercentApply.Enabled = false;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        //private void cmbVendorRatesBranches_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        btnSyncVendorRates.Enabled = false;
        //        btnUpdateVendorRates.Enabled = false;

        //        if (cmbVendorRatesBranches.SelectedIndex > -1)
        //        {
        //            cmbVendor.DataSource = null;
        //            int sample = 0;
        //            if (int.TryParse(cmbVendorRatesBranches.SelectedValue.ToString(), out sample))
        //            {
        //                cmbVendor.DataSource = DBHelper.GetAllVendorsByBranch(cmbVendorRatesBranches.SelectedValue.ToString());
        //                if (cmbVendor.DataSource != null)
        //                {
        //                    cmbVendor.DisplayMember = "Vendor";
        //                    cmbVendor.ValueMember = "ID";

        //                    if (cmbVendorRatesBranches.Text == "Central")
        //                    {
        //                        btnSyncVendorRates.Enabled = false;
        //                        btnUpdateVendorRates.Enabled = true;
        //                        cmbPercent.SelectedIndex = 0;
        //                        cmbPercent.Enabled = true;
        //                        btnPercentApply.Enabled = true;
        //                    }
        //                    else
        //                    {
        //                        btnSyncVendorRates.Enabled = true;
        //                        btnUpdateVendorRates.Enabled = false;
        //                        cmbPercent.Enabled = false;
        //                        btnPercentApply.Enabled = false;
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        WriteToEventViewer(ex.Message);
        //        MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }
        //}

        private void btnGetVendorRates_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbVendorRatesBranches.SelectedValue.ToString();
                dgVendorRates.DataSource = DBHelper.GetVendorRatesByBranchAndCompany(branchSelected, cmbVendor.SelectedValue.ToString());
                Cursor.Current = Cursors.Default;
                if (dgVendorRates.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    dgVendorRates.Columns[0].Width = 100;
                    dgVendorRates.Columns[0].ReadOnly = true;
                    dgVendorRates.Columns[1].Width = 300;
                    dgVendorRates.Columns[1].ReadOnly = true;
                    dgVendorRates.Columns[2].Visible = false;
                    dgVendorRates.Columns[2].ReadOnly = true;
                    dgVendorRates.Columns[3].ReadOnly = false;
                    dgVendorRates.Columns[4].Visible = false;
                    dgVendorRates.Focus();
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgVendorRates_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (dgVendorRates.SelectedRows.Count > 0)
                {
                    dgVendorRates.SelectedRows[0].Cells[3].Selected = true;
                    if (e.KeyChar > 47 && e.KeyChar < 58)
                    {
                        dgVendorRates.SelectedRows[0].Cells[3].Value = double.Parse(((char)e.KeyChar).ToString());
                        dgVendorRates.BeginEdit(false);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgVendorRates_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string value = dgVendorRates[e.ColumnIndex, e.RowIndex].Value.ToString();

                float result = 0;
                float.TryParse(value, out result);
                if (result < 0)
                {
                    dgVendorRates[e.ColumnIndex, e.RowIndex].Value = 0;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgVendorRates_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = false;
        }

        private void btnUpdateVendorRates_Click(object sender, EventArgs e)
        {
            try
            {
                double price = 0.0;
                List<VendorItem> items = new List<VendorItem>();
                foreach (DataGridViewRow row in dgVendorRates.Rows)
                {
                    if (row.Cells[3].Value.ToString() == "0" || row.Cells[3].Value.ToString() == "0.0" || (row.Cells[3].Value.ToString() == row.Cells[4].Value.ToString()))
                    {
                        continue;
                    }

                    price = double.Parse(row.Cells[3].Value.ToString());
                    if (price != 0)
                    {
                        items.Add(new VendorItem { ItemCode = int.Parse(row.Cells[0].Value.ToString()), Price = price });
                    }
                }

                int result = DBHelper.UpdateVendorRates(cmbVendor.SelectedValue.ToString(), items);

                if (result > 0)
                {
                    MessageBox.Show("Vendor Rates Updated Successfully", "Vendor Rates Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    dgVendorRates.DataSource = null;
                }
                else
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSyncVendorRates_Click(object sender, EventArgs e)
        {
            try
            {
                if (DialogResult.OK == MessageBox.Show("Do you want to Sync Vendor Rates in " + cmbVendorRatesBranches.Text + " Branch?", "Sync Vendor Rates", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.SyncVendorRatesByBranch(cmbVendorRatesBranches.SelectedValue.ToString()) == 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Vendor Rates Synced Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        dgVendorRates.DataSource = null;
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Some Unknown Error has Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPercentApply_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgVendorRates.DataSource == null)
                {
                    MessageBox.Show("There are no items to Apply.", "No Items", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (cmbPercent.SelectedIndex > -1)
                {
                    double percentage = double.Parse(cmbPercent.Text.ToString());

                    foreach (DataGridViewRow row in dgVendorRates.Rows)
                    {
                        row.Cells[3].Value = (double.Parse(row.Cells[4].Value.ToString()) * ((100 - percentage) / 100)).ToString();
                    }
                }
                else
                {
                    MessageBox.Show("Please select the Percentage to Apply for all items.", "Select Percentage", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Cancel

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    tabControl1.SelectTab(16);
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnCancelBulk_Click(object sender, EventArgs e)
        {
            try
            {
                tabControl1.SelectTab(17);

                if (BranchesData == null)
                    BranchesData = DBHelper.GetBranches();
                //DataTable dt = BranchesData;
                cmbBranchBulk.DataSource = BranchesData;
                cmbBranchBulk.DisplayMember = "BranchName";
                cmbBranchBulk.ValueMember = "BranchID";
                dgMainBulk.DataSource = null;
                dgSubBulk.DataSource = null;
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancelVendor_Click(object sender, EventArgs e)
        {
            tabControl1.SelectTab(18);

            if (BranchesData == null)
                BranchesData = DBHelper.GetBranches();
            //DataTable dt = BranchesData;
            cmbBranchVendor.DataSource = BranchesData;
            cmbBranchVendor.DisplayMember = "BranchName";
            cmbBranchVendor.ValueMember = "BranchID";
            dgvMainVendorBills.DataSource = null;
            dgvSubVendorBills.DataSource = null;
        }

        private void btnCreditNotes_Click(object sender, EventArgs e)
        {
            tabControl1.SelectTab(19);

            if (BranchesData == null)
                BranchesData = DBHelper.GetBranches();
            //DataTable dt = BranchesData;
            cmbBranchCreditNote.DataSource = BranchesData;
            cmbBranchCreditNote.DisplayMember = "BranchName";
            cmbBranchCreditNote.ValueMember = "BranchID";
            dgvMainCreditNotes.DataSource = null;
            dgvSubCreditNotes.DataSource = null;
        }

        #endregion

        #region Suppliers

        private void btnSuppliersAdd_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    tabControl1.SelectTab(20);
                    dgvSuppliers.DataSource = DBHelper.GetAllSuppliers();
                    if (dgvSuppliers.DataSource != null)
                    {
                        dgvSuppliers.Columns[0].Width = 55;
                        dgvSuppliers.Columns[1].Width = 250;
                    }
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnAddSupplier_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtSupplier.Text != string.Empty)
                {
                    foreach (DataGridViewRow row in dgvSuppliers.Rows)
                    {
                        if (row.Cells[1].Value.ToString() == txtSupplier.Text)
                        {
                            MessageBox.Show("Supplier Already Existing", "Supplier Exists", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    Cursor.Current = Cursors.WaitCursor;
                    if (DBHelper.AddSupplier(txtSupplier.Text) > 0)
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Supplier Added Successfully", "Supplier Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnSuppliersAdd_Click(sender, e);
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Supplier Adding Failed", "Supplier Adding Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Please Enter The Supplier", "Supplier Invalid", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region View/Cancel Bulk Order

        private void btnCancelBulkOrder_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            isBranchSelected = false;
            try
            {
                if (dgMainBulk.DataSource != null)
                {
                    if (!(bool.Parse(dgMainBulk.SelectedRows[0].Cells[5].Value.ToString())))
                    {
                        if (DBHelper.CancelBulkOrder(dgMainBulk.SelectedRows[0].Cells[0].Value.ToString(), branchSelected, isBranchSelected) > 0)
                        {
                            Cursor.Current = Cursors.Default;
                            MessageBox.Show("Cancelled the Bulk Order Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            btnBulkOrders_Click(sender, e);
                        }
                        else
                        {
                            Cursor.Current = Cursors.Default;
                            MessageBox.Show("Unable to Cancel the Bulk Order", "Cancel Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Bulk Order Already Cancelled.", "Bulk Order Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnBulkOrders_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbBranchBulk.SelectedValue.ToString();
                isBranchSelected = chkBulkBranch.Checked;
                dgMainBulk.DataSource = DBHelper.GetBulkOrders(cmbBranchBulk.SelectedValue.ToString(), dpDateBulk.Value, chkMonthBulk.Checked, false);
                Cursor.Current = Cursors.Default;
                if (dgMainBulk.DataSource == null)
                {
                    dgSubBulk.DataSource = null;
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgMainBulk_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgMainBulk.SelectedRows.Count > 0)
                {
                    string billNo = dgMainBulk.SelectedRows[0].Cells[0].Value.ToString();

                    if (billNo != string.Empty)
                    {
                        bool IsException = false;

                        dgSubBulk.DataSource = DBHelper.GetBillDetailsByBillNo(billNo, cmbBranchBulk.SelectedValue.ToString());

                        if (IsException)
                        {
                            dgSubBulk.DataSource = null;
                            MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (dgSubBulk.DataSource != null)
                        {
                            dgSubBulk.Columns[0].Width = 80;
                            dgSubBulk.Columns[1].Width = 80;
                            dgSubBulk.Columns[2].Width = 180;
                            dgSubBulk.Columns[3].Width = 80;
                        }
                        else
                        {
                            dgSubBulk.DataSource = null;
                            MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region View/Cancel Vendor Bills

        private void btnGetVendorBills_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbBranchVendor.SelectedValue.ToString();
                isBranchSelected = chkVendorBranch.Checked;
                dgvMainVendorBills.DataSource = DBHelper.GetVendorBills(cmbBranchVendor.SelectedValue.ToString(), dpDateVendor.Value, chkVendorMonth.Checked, chkVendorBranch.Checked);
                Cursor.Current = Cursors.Default;
                if (dgvMainVendorBills.DataSource == null)
                {
                    dgvSubVendorBills.DataSource = null;
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    dgvMainVendorBills.Columns[0].Width = 300;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvMainVendorBills_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgvMainVendorBills.SelectedRows.Count > 0)
                {
                    string billNo = dgvMainVendorBills.SelectedRows[0].Cells[1].Value.ToString();

                    if (billNo != string.Empty)
                    {
                        bool IsException = false;

                        dgvSubVendorBills.DataSource = DBHelper.GetBillDetailsByBillNo(billNo, cmbBranchVendor.SelectedValue.ToString());

                        if (IsException)
                        {
                            dgvSubVendorBills.DataSource = null;
                            MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (dgvSubVendorBills.DataSource != null)
                        {
                            dgvSubVendorBills.Columns[0].Width = 80;
                            dgvSubVendorBills.Columns[1].Width = 80;
                            dgvSubVendorBills.Columns[2].Width = 180;
                            dgvSubVendorBills.Columns[3].Width = 80;
                        }
                        else
                        {
                            dgvSubVendorBills.DataSource = null;
                            MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancelVendorBill_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            isBranchSelected = false;
            try
            {
                if (dgvMainVendorBills.DataSource != null)
                {
                    if (!(bool.Parse(dgvMainVendorBills.SelectedRows[0].Cells[4].Value.ToString())))
                    {
                        if (DBHelper.CancelVendorBill(dgvMainVendorBills.SelectedRows[0].Cells[1].Value.ToString(), branchSelected, isBranchSelected) > 0)
                        {
                            Cursor.Current = Cursors.Default;
                            MessageBox.Show("Cancelled the Vendor Bill Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            btnGetVendorBills_Click(sender, e);
                        }
                        else
                        {
                            Cursor.Current = Cursors.Default;
                            MessageBox.Show("Unable to Cancel the Vendor Bill", "Cancel Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Vendor Bill Already Cancelled.", "Bulk Order Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Credit Notes

        private void btnGetCreditNotes_Click(object sender, EventArgs e)
        {
            try
            {
                branchSelected = cmbBranchCreditNote.SelectedValue.ToString();
                isBranchSelected = chkCreditBranch.Checked;
                Cursor.Current = Cursors.WaitCursor;
                isBranchSelected = false;
                dgvMainCreditNotes.DataSource = DBHelper.GetCreditNotes(cmbBranchCreditNote.SelectedValue.ToString(), dtpDateCreditNote.Value, chkCreditMonth.Checked, chkCreditBranch.Checked);
                Cursor.Current = Cursors.Default;
                if (dgvMainCreditNotes.DataSource == null)
                {
                    dgvSubCreditNotes.DataSource = null;
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    dgvMainCreditNotes.Columns[0].Width = 300;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvMainCreditNotes_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgvMainCreditNotes.SelectedRows.Count > 0)
                {
                    string billNo = dgvMainCreditNotes.SelectedRows[0].Cells[1].Value.ToString();

                    if (billNo != string.Empty)
                    {
                        bool IsException = false;

                        dgvSubCreditNotes.DataSource = DBHelper.GetBillDetailsByBillNo(billNo, cmbBranchCreditNote.SelectedValue.ToString());

                        if (IsException)
                        {
                            dgvSubCreditNotes.DataSource = null;
                            MessageBox.Show("Some Error Has Occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        if (dgvSubCreditNotes.DataSource != null)
                        {
                            dgvSubCreditNotes.Columns[0].Width = 80;
                            dgvSubCreditNotes.Columns[1].Width = 80;
                            dgvSubCreditNotes.Columns[2].Width = 180;
                            dgvSubCreditNotes.Columns[3].Width = 80;
                        }
                        else
                        {
                            dgvSubCreditNotes.DataSource = null;
                            MessageBox.Show("No Data Available.", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancelCreditNotes_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            isBranchSelected = false;
            try
            {
                if (dgvMainCreditNotes.DataSource != null)
                {
                    if (!(bool.Parse(dgvMainCreditNotes.SelectedRows[0].Cells[4].Value.ToString())))
                    {
                        if (DBHelper.CancelVendorBill(dgvMainCreditNotes.SelectedRows[0].Cells[1].Value.ToString(), branchSelected, isBranchSelected) > 0)
                        {
                            Cursor.Current = Cursors.Default;
                            MessageBox.Show("Cancelled the Credit Note Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            btnGetCreditNotes_Click(sender, e);
                        }
                        else
                        {
                            Cursor.Current = Cursors.Default;
                            MessageBox.Show("Unable to Cancel the Credit Note", "Cancel Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Credit Note Already Cancelled.", "Bulk Order Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Departments

        private void btnDept_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgvDepartments.DataSource = null;

                    DataTable dt = new DataTable();
                    dt.Columns.Add("BranchID");
                    dt.Columns.Add("BranchName");

                    dt.Rows.Add(0, "Central");
                    cmbBranchDept.DataSource = dt;
                    cmbBranchDept.DisplayMember = "BranchName";
                    cmbBranchDept.ValueMember = "BranchID";
                    tabControl1.SelectTab(21);
                    //txtVendor.Enabled = cmbIsValidVendor.Enabled = false;
                    cmbIsValidVendor.SelectedIndex = -1;
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void btnGetDepartments_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                branchSelected = cmbBranchDept.SelectedValue.ToString();

                txtVendor.Enabled = false;
                cmbIsValidVendor.Enabled = true;
                btnNewVendor.Enabled = true;
                //cmbIsValidVendor.SelectedIndex = -1;
                dgvDepartments.DataSource = DBHelper.GetAllDepartmentsByBranch(branchSelected);
                Cursor.Current = Cursors.Default;
                if (dgvDepartments.DataSource == null)
                {
                    MessageBox.Show("No Data Available", "No Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtVendor.Clear();
                    return;
                }
                else
                {
                    dgvDepartments.Columns[0].Visible = false;
                    dgvDepartments.Columns[1].Width = 80;
                    dgvDepartments.Columns[2].Width = 200;
                    dgvDepartments.Columns[3].Width = 100;
                    txtDeptCode.Enabled = false;
                    txtDeptName.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void dgvDepartments_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgvDepartments.SelectedRows.Count > 0)
                {
                    txtDeptCode.Text = dgvDepartments.SelectedRows[0].Cells[1].Value.ToString();
                    txtDeptName.Text = dgvDepartments.SelectedRows[0].Cells[2].Value.ToString();
                    chkSlipReqd.Checked = bool.Parse(dgvDepartments.SelectedRows[0].Cells[3].Value.ToString());
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Some Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddNewDept_Click(object sender, EventArgs e)
        {
            try
            {
                if (cmbBranchDept.SelectedValue != null)
                {
                    if (cmbBranchDept.SelectedValue.ToString() == "0")
                    {
                        dgvDepartments.DataSource = null;
                        txtDeptCode.Clear();
                        txtDeptName.Clear();
                        chkSlipReqd.Checked = false;
                        btnAddNewVendor.Enabled = txtDeptCode.Enabled = txtDeptName.Enabled = true;
                        cmbIsValidVendor.SelectedIndex = -1;
                    }
                    else
                    {
                        MessageBox.Show("Please Select Central in the Branch Drop Down", "Select Central Branch", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddUpdateDept_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                int result = 0;
                if (dgvDepartments.DataSource != null && dgvDepartments.SelectedRows.Count > 0)
                {
                    result = DBHelper.AddOrUpdateDepartment(dgvDepartments.SelectedRows[0].Cells[0].Value.ToString(), dgvDepartments.SelectedRows[0].Cells[1].Value.ToString(), dgvDepartments.SelectedRows[0].Cells[2].Value.ToString(), chkSlipReqd.Checked);
                }
                else
                {
                    if (txtDeptCode.Text.Trim() == string.Empty || txtDeptName.Text.Trim() == string.Empty)
                    {
                        MessageBox.Show("Please Fill All the Mandatory Values", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    result = DBHelper.AddOrUpdateDepartment("0", txtDeptCode.Text, txtDeptName.Text, chkSlipReqd.Checked);
                }

                Cursor.Current = Cursors.Default;
                if (result > 0)
                {
                    MessageBox.Show("Department Added/Updated Successfully", "Department Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtDeptCode.Clear();
                    txtDeptName.Clear();
                    chkSlipReqd.Checked = false;
                    btnGetDepartments_Click(sender, e);
                }
                else if (result == -1)
                {
                    MessageBox.Show("Department Already Exists", "Department Exists", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                Cursor.Current = Cursors.Default;
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Common Codes

        private void btnCommonCodes_Click(object sender, EventArgs e)
        {
            if (IsLoggedIn)
            {
                try
                {
                    dgvCommonCodes.DataSource = DBHelper.GetCommonCodes();
                    if (dgvCommonCodes != null && dgvCommonCodes.Rows.Count > 0)
                    {
                        dgvCommonCodes.Columns[0].Width = 40;
                        dgvCommonCodes.Columns[1].Width = 475;
                    }
                    tabControl1.SelectTab(22);
                }
                catch (Exception ex)
                {
                    WriteToEventViewer(ex.Message);
                    MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                tabControl1.SelectTab(1);
                txtUserName.Focus();
            }
        }

        private void dgvCommonCodes_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (dgvCommonCodes.SelectedRows != null && dgvCommonCodes.SelectedRows.Count > 0)
                {
                    txtCommonCode.Text = dgvCommonCodes.SelectedRows[0].Cells[1].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddNewCommonCode_Click(object sender, EventArgs e)
        {
            try
            {
                dgvCommonCodes.DataSource = null;
                txtCommonCode.Clear();
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddCommonCode_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                int result = 0;
                if (dgvCommonCodes.DataSource != null && dgvCommonCodes.SelectedRows.Count > 0)
                {
                    result = DBHelper.AddOrUpdateCommonCode(dgvCommonCodes.SelectedRows[0].Cells[0].Value.ToString(), txtCommonCode.Text);
                }
                else
                {
                    if (txtCommonCode.Text.Trim() == string.Empty || txtCommonCode.Text.Trim() == string.Empty)
                    {
                        MessageBox.Show("Please Fill All the Mandatory Values", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    result = DBHelper.AddOrUpdateCommonCode("0", txtCommonCode.Text);
                }

                Cursor.Current = Cursors.Default;
                if (result > 0)
                {
                    MessageBox.Show("Common Code Added/Updated Successfully", "Common Code Added/Updated", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtCommonCode.Clear();
                    btnCommonCodes_Click(sender, e);
                }
                else
                {
                    MessageBox.Show("Some unknown error has occurred.", "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                WriteToEventViewer(ex.Message);
                MessageBox.Show("Some unknown error has occurred.\r\nError Msg : " + ex.Message, "Unknown Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUserName.Text.Trim().ToLower() == "ksbakers.managingbakery" || txtPassword.Text.Trim().ToLower() == "managing." + DateTime.Now.ToString("ddMMyyyy"))
                {
                    IsLoggedIn = true;
                    tabControl1.SelectTab(0);
                    return;
                }
                else
                {
                    MessageBox.Show("Invalid Details", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPassword.Clear();
                    txtPassword.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtPassword_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                btnLogin_Click(sender, e);
        }

        private void btnMain_Click(object sender, EventArgs e)
        {
            tabControl1.SelectTab(0);
        }
    }
}
